<!--
* description: 销售计划跟踪
* author: wangml
* createdDate: 2020-12-01
-->

<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-api-style="apiStyle"
      :dynamic-page-size="10"
      :page-size-array="newpagesizeArr"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
      @hiddenColData="hiddenColData"
    />
    <edit
      :title="editTitle"
      :popups-visible.sync="showdia"
      :edit-forms="editForms"
      :edit-width="editWidth"
      :dynamic-edit-row-data="rowData"
      popups-state="edit"
      @close="close1"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/planReport'
import { orgApis } from '@/api/vesalesapi'
import edit from '@/views/ve/planReport/headquartersConfirmWeekSalesPlan/edit1'
import commData from '../common/index.js'

export default {
  name: 'SalesPlanTracking',
  components: {
    OneTableTemplate,
    edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      newpagesizeArr: ['10', '50', '100', '500', '1000', '2000'],
      rowData: {},
      editTitle: '销售计划跟踪',
      editWidth: '45%',
      editForms: [
        {
          // title: '保险费发票',
          tid: 1,
          data: [
            {
              compKey: 'carSeries',
              labelName: '车系名称：',
              codeField: 'carSeriesId',
              textField: 'carSeriesCn',
              oFields: 'carSeriesId,carSeriesCn',
              customObj: { api: orgApis.listOfCarSeries, selectType: '1' },
              component: () => import('@/components/org/commonSelect'),
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'carConfig',
              labelName: '基础车型名称：',
              codeField: 'carConfigId',
              textField: 'carConfigCn',
              disabled: true,
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carConfigId,carConfigCn',
              parentFileds: 'value:carSeriesId,disabled:carSeriesId-carConfigId--false',
              customObj: {
                listQuery: { carSeriesId: '' },
                api: orgApis.listOfCarModel, selectType: '1'
              },
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'optionalPag',
              labelName: '选装包：',
              codeField: 'optionalPagId',
              textField: 'optionalPagName',
              disabled: true,
              component: () => import('@/components/org/commonSelect'),
              parentFileds: 'value:carConfigId|carSeriesId,disabled:carConfigId-optionalPagId--false',
              oFields: 'optionalPagId,optionalPagName',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: ''
                },
                api: orgApis.listOfPackage, selectType: '1'
              },
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'carColor',
              labelName: '车身颜色：',
              codeField: 'carColorId',
              textField: 'carColorName',
              disabled: true,
              component: () => import('@/components/org/commonSelect'),
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId,disabled:optionalPagId-carColorId--false',
              oFields: 'carColorId,carColorName',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: orgApis.listOfCarColor, selectType: '1'
              },
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'carIncolor',
              labelName: '内饰颜色：',
              codeField: 'carIncolorId',
              textField: 'carIncolorName',
              disabled: true,
              component: () => import('@/components/org/commonSelect'),
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId,disabled:optionalPagId-carIncolorId--false',
              oFields: 'carIncolorId,carIncolorName',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: orgApis.listOfCarInterior, selectType: '1'
              },
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey2',
              labelName: '车型选配器：',
              codeField: 'ttCode',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'comKey2',
              labelName: '计划月份：',
              codeField: 'planMonth',
              disabled: true,
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'month',
              format: 'yyyy-MM',
              dateOptionsType: '3',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey5',
              labelName: '计划周度：',
              codeField: 'planWeek',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              // type: 'dropdownList',
              isMust: true,
              isRequire: false
            },
            {
              compKey: 'compKey6',
              labelName: '是否紧急订单：',
              codeField: 'urgent',
              isRequire: true,
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: true,
              oFields: 'isDefaultAddr,isDefaultName',
              options: [
                { isDefaultAddr: '1', isDefaultName: '是' },
                { isDefaultAddr: '0', isDefaultName: '否' }
              ]
            }
          ]
        }
      ],
      curPopupsVisible: false,
      genCodeFiled: null,
      selectList: [],
      clickRowsData: {},
      popstate: 'add',
      showdia: false,
      // 指定请求类型 可以统一在 utils/config.js中配置
      apiStyle: 'restful',
      dynamicApiConfig: api.SalePlanTrackingQuery,
      refreshTableKey: '0',
      ruleSettingShow: false,
      // table表格查询API配置对象
      // 动态组件-查询条件
      tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
            : [
              ...commData.ModelOptions(2),
              {
                compKey: 'comKey6',
                labelName: '销售计划号：',
                codeField: 'salePlanCode',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey7',
                labelName: '计划月份：',
                codeField: 'planMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                format: 'yyyy-MM',
                // dateOptionsType: '3',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey8',
                labelName: '计划周度：',
                codeField: 'planWeek',
                oFields: 'planWeek,planWeekText',
                isMul: true,
                component: () => import('@/components/org/commonSelect'),
                type: 'dropdownList',
                options: [],
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey9',
                labelName: '计划状态：',
                codeField: 'planStatus',
                lookuptype: 'VE9000',
                isMul: true,
                component: () => import('@/components/org/commonSelect'),
                type: 'dropdownList',
                isMust: false,
                span: 6
              },
              {
                compKey: 'compKey10',
                labelName: '制作时间：',
                codeField: 'startTime,endTime',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'daterange',
                isMul: false,
                isMust: false
              }

            ],
      formField: {
        planMonth: '',
        salePlanCode: '',
        planWeek: '',
        planStatus: '',
        startTime: '',
        endTime: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: ''
      },
      // 动态组件-按钮
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'comKey1',
            type: 'primary',
            size: 'small',
            name: 'search',
            position: 'right',
            clickEvent: () => this.queryTable(),
            text: '查询'
          },
          {
            compKey: 'comKey0',
            type: '',
            size: 'small',
            name: 'reset',
            position: 'right',
            clickEvent: () => this.reset(),
            text: '重置'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: 'SMSsending',
            position: 'left',
            disabled: true,
            clickEvent: () => this.send(),
            text: '发送'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: 'quanbushanchu',
            position: 'left',
            disabled: true,
            clickEvent: () => this.delData(),
            text: '删除'
          },
          {
            compKey: 'comKey4',
            type: '',
            size: 'small',
            name: 'export',
            position: 'left',
            clickEvent: () => this.export(),
            text: '导出'
          }

        ],
      // 动态组件-表格网格列
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            label: '操作',
            minWidth: 180,
            fixed: true,
            isComponent: true,
            comps: [
              {
                compKey: 'propKey1',
                labelName: '编辑',
                component: () => import('@/components/org/linkButton'),
                clickEvent: (index) => this.edit(index),
                rowFileds: 'show:planStatus-2'
              }
            ]
          },
          {
            prop: 'planStatusCode',
            label: '计划状态'
          },

          {
            prop: 'ttCode',
            label: '22位码',
            width: 180
          },
          {
            prop: 'salePlanCode',
            label: '销售计划号',
            width: 180
          },
          {
            prop: 'urgent',
            label: '是否紧急订单',
            width: 180
          },
          {
            prop: 'planMonth',
            label: '计划月份'
          },
          {
            prop: 'planWeek',
            label: '计划周度'
          },
          {
            prop: 'carSeriesCode',
            label: '车系编码'
          },
          {
            prop: 'carSeriesCn',
            label: '车系名称'
          },
          {
            prop: 'carConfigCode',
            label: '基础车型编码',
            width: 120
          },
          {
            prop: 'carConfigCn',
            label: '基础车型名称',
            width: 110
          },
          {
            prop: 'optionalPagCode',
            label: '选装包编码'
          },
          {
            prop: 'optionalPagName',
            label: '选装包名称'
          },
          {
            prop: 'carColorCode',
            label: '车身颜色编码'
          },
          {
            prop: 'carColorName',
            label: '车身颜色名称'
          },
          {
            prop: 'carIncolorCode',
            label: '内饰颜色编码'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色名称'
          },
          {
            prop: 'hostLimitState',
            label: '限制类型'
          },
          {
            prop: 'limitEasonRemark',
            label: '备注'
          },
          {
            prop: 'createdDate',
            label: '制作时间',
            width: 120
          }

        ],
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList = selection
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  watch: {
    'formField.planMonth': {
      handler(val) {
        if (val) {
          this.formField.planWeek = ''
          var thisMonth = val + '-01'
          this.getweekByplan(thisMonth)
        } else {
          this.getPlanWeek()
        }
      }
    }
  },
  mounted() {
    // 列表查询
    this.getPlanWeek()
    this.queryTable(1)
  },
  methods: {
    close1(type) {
      this.showdia = false
      if (type === '1') {
        this.queryTable(1)
      }
    },
    // 获取计划月份周度
    getweekByplan(planMonth) {
      this.$requestAPI({
        apiUrl: api.weekPlan.APIUrl,
        variables: {
          planMonth: planMonth
        }
      }).then(res => {
        if (res.result === '1') {
          const optionList = []
          var arr = res.rows
          arr.forEach(item => {
            optionList.push({
              planWeek: item.PLAN_WEEK,
              planWeekText: item.PLAN_WEEK
            })
          })
          this.tableComponents[7].options = optionList
        } else {
          this.$message(res.msg)
        }
      })
    },
    // 计划周度
    getPlanWeek() {
      const optionList = []
      for (let i = 1; i < 53; i++) {
        const num = i
        optionList.push({
          planWeek: `W${num}`,
          planWeekText: `W${num}`
        })
      }
      this.tableComponents[7].options = optionList
    },
    handle() { },
    edit(idx) {
      this.rowData = this.$refs.multipleTable.list[idx]
      this.showdia = true
    },
    send() {
      this.$confirm('确定要发送吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const OrderStatus = this.selectList.every((item) => {
          return item.planStatus === this.selectList[0].planStatus
        })
        if (!OrderStatus) {
          this.$message('不同计划状态不可同时操作！')
          return
        }
        const that = this
        this.$requestAPI({
          apiUrl: api.SalePlanTrackingSend.APIUrl,
          variables: {
            list: that.selectList
          }
        }).then(res => {
          if (res.result === '1') {
            this.$message(res.msg)
            this.$refs['multipleTable'].queryTable(1)
          } else {
            this.$message(res.msg)
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },
    // getSelectable(data) {
    //   if (data.planStatus === '已发送' || data.planStatus === '驳回') {
    //     return true
    //   }
    //   return false
    // },
    export() {
      // fileName -> 选装包维护20201222181629.xlsx
      const arr = []
      this.selectList.forEach(data => {
        arr.push(data.salesPlanId)
      })
      const reqData = this.$utils.deepCopy(this.formField)
      if (arr.length) {
        reqData.salesPlanId = arr.join(',')
      } else {
        reqData.salesPlanId = ''
      }
      const title = '销售计划跟踪'
      const fileSuffix = this.$config.excelExp
      const fileName = this.$utils.fileNameWithTime(`${title}${fileSuffix}`)
      this.$requestAPI({
        apiUrl: api.SalePlanTrackingExport.APIUrl,
        variables: { ...reqData, dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    // 自动生成codeField
    genUtil: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
    // 保存 或新增 后会调用此方法
    popClose(type) {
      this.showdia = false
      if (type === 1) {
        this.queryTable(1)
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        if (isCheck) {
          const str = selection.every((item) => {
            return item.planStatus === '2'
          })
          btns[0].disabled = !str
          const del = selection.every((item) => {
            return item.planStatus === '1' || item.planStatus === '2' || item.planStatus === '6'
          })
          btns[1].disabled = !del
        } else {
          btns.forEach((item) => {
            item.disabled = true
          })
        }
      }
    },

    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    },

    // 新增
    // add() {
    //   this.clickRowsData = {}
    //   this.popstate = 'add'
    //   this.showdia = true
    // },
    selectRowsData(rowdata) {

    },

    // 查看附件
    checkFile(index, type) {
      // location.href = process.env.VUE_APP_BASE_API + this.$refs['multipleTable'].list[index].downloadUrl
      window.open(this.$refs['multipleTable'].list[index][type])
    },

    // 删除按钮单条删除
    delOneData(row) {
      const data = [this.$refs['multipleTable'].list[row]]
      this.delData(data)
    },

    // 数据批量删除
    delSeleteData() {
      const data = this.$refs['multipleTable'].$refs['multipleTable'].selection
      this.delData(data)
    },

    // 删除
    delData() {
      const OrderStatus = this.selectList.every((item) => {
        return item.planStatus === this.selectList[0].planStatus
      })
      if (!OrderStatus) {
        this.$message('不同计划状态不可同时操作！')
        return
      }
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateControlIds = []
        const arr = []
        const arr1 = []
        const assignState = []
        const planStatus = []
        if (this.selectList.length) {
          this.selectList.forEach(data => {
            arr.push(data.updateControlId)
            updateControlIds.push(data.updateControlIds)
            arr1.push(data.salesPlanId)
            assignState.push(data.assignState)
            planStatus.push(data.planStatus)
          })
        } else {
          this.$message('没有选择!')
        }
        this.$requestAPI({
          apiUrl: api.SalePlanTrackingDelete.APIUrl,
          variables: {
            list: this.selectList
          }
          // method: 'POST', // 默认post
          // contentType: '', // 默认 'application/json; charset=UTF-8'
          // lock: '',
          // urlType: 'GET' // 处理非json请求
        }).then(res => {
          if (res.result === '1') {
            this.$message(res.msg)
            this.$refs['multipleTable'].queryTable(1)
          } else {
            this.$message(res.msg)
          }
        })
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>

